<template>
  <div class="lending-process">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>放款处理</h3>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="贷款编号">
          <el-input v-model="searchForm.loanNo" placeholder="请输入贷款编号" />
        </el-form-item>
        <el-form-item label="客户姓名">
          <el-input v-model="searchForm.customerName" placeholder="请输入客户姓名" />
        </el-form-item>
        <el-form-item label="处理状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态">
            <el-option label="待处理" value="pending" />
            <el-option label="处理中" value="processing" />
            <el-option label="已完成" value="completed" />
            <el-option label="处理失败" value="failed" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 处理列表 -->
      <el-table :data="processList" style="width: 100%" v-loading="loading">
        <el-table-column prop="loanNo" label="贷款编号" width="180" />
        <el-table-column prop="customerName" label="客户姓名" width="120" />
        <el-table-column prop="amount" label="放款金额" width="150">
          <template #default="scope">
            {{ formatAmount(scope.row.amount) }}
          </template>
        </el-table-column>
        <el-table-column prop="bankInfo" label="收款账户" width="300">
          <template #default="scope">
            <div>{{ scope.row.bankName }}</div>
            <div style="color: #666; font-size: 13px">{{ scope.row.bankAccount }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="payChannel" label="支付渠道" width="120" />
        <el-table-column prop="processStatus" label="处理进度" width="200">
          <template #default="scope">
            <el-progress
              :percentage="scope.row.processPercentage"
              :status="getProgressStatus(scope.row.status)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" fixed="right" width="180">
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="handleProcess(scope.row)"
              v-if="scope.row.status === 'pending'"
            >
              处理
            </el-button>
            <el-button
              link
              type="success"
              @click="handleConfirm(scope.row)"
              v-if="scope.row.status === 'processing'"
            >
              确认
            </el-button>
            <el-button
              link
              type="primary"
              @click="viewDetail(scope.row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 处理对话框 -->
    <el-dialog
      v-model="processDialogVisible"
      title="放款处理"
      width="60%"
    >
      <el-steps :active="activeStep" finish-status="success" class="process-steps">
        <el-step title="信息核验" />
        <el-step title="资金准备" />
        <el-step title="放款执行" />
        <el-step title="完成确认" />
      </el-steps>

      <div class="step-content">
        <!-- 信息核验步骤 -->
        <div v-if="activeStep === 0">
          <el-form ref="verifyFormRef" :model="verifyForm" label-width="120px">
            <el-descriptions title="放款信息" :column="2" border>
              <el-descriptions-item label="贷款编号">{{ currentLoan.loanNo }}</el-descriptions-item>
              <el-descriptions-item label="客户姓名">{{ currentLoan.customerName }}</el-descriptions-item>
              <el-descriptions-item label="放款金额">{{ formatAmount(currentLoan.amount) }}</el-descriptions-item>
              <el-descriptions-item label="收款账号">{{ currentLoan.bankAccount }}</el-descriptions-item>
              <el-descriptions-item label="开户行">{{ currentLoan.bankName }}</el-descriptions-item>
              <el-descriptions-item label="支付渠道">{{ currentLoan.payChannel }}</el-descriptions-item>
            </el-descriptions>

            <el-form-item label="信息确认" prop="infoConfirm">
              <el-checkbox v-model="verifyForm.infoConfirm">确认以上信息无误</el-checkbox>
            </el-form-item>

            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="verifyForm.remark"
                type="textarea"
                rows="3"
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </el-form>
        </div>

        <!-- 资金准备步骤 -->
        <div v-if="activeStep === 1">
          <el-form ref="fundFormRef" :model="fundForm" label-width="120px">
            <el-form-item label="资金来源" prop="fundSource">
              <el-select v-model="fundForm.fundSource" placeholder="请选择资金来源">
                <el-option label="自有资金" value="own" />
                <el-option label="合作方资金" value="partner" />
                <el-option label="其他来源" value="other" />
              </el-select>
            </el-form-item>

            <el-form-item label="资金账户" prop="fundAccount">
              <el-input v-model="fundForm.fundAccount" placeholder="请输入资金账户" />
            </el-form-item>

            <el-form-item label="账户余额">
              <span class="amount-text">{{ formatAmount(1000000) }}</span>
            </el-form-item>

            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="fundForm.remark"
                type="textarea"
                rows="3"
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </el-form>
        </div>

        <!-- 放款执行步骤 -->
        <div v-if="activeStep === 2">
          <el-form ref="executeFormRef" :model="executeForm" label-width="120px">
            <el-form-item label="支付流水号" prop="transactionNo">
              <el-input v-model="executeForm.transactionNo" placeholder="请输入支付流水号" />
            </el-form-item>

            <el-form-item label="支付状态">
              <el-tag :type="executeForm.status === 'success' ? 'success' : 'warning'">
                {{ executeForm.status === 'success' ? '支付成功' : '支付处理中' }}
              </el-tag>
            </el-form-item>

            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="executeForm.remark"
                type="textarea"
                rows="3"
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </el-form>
        </div>

        <!-- 完成确认步骤 -->
        <div v-if="activeStep === 3">
          <el-result
            icon="success"
            title="放款处理完成"
            :sub-title="'放款金额：' + formatAmount(currentLoan.amount)"
          >
            <template #extra>
              <el-button type="primary" @click="finishProcess">确认完成</el-button>
            </template>
          </el-result>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="processDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="nextStep"
            v-if="activeStep < 3"
          >
            下一步
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="处理详情"
      width="70%"
    >
      <el-descriptions title="基本信息" :column="2" border>
        <el-descriptions-item label="贷款编号">{{ currentLoan.loanNo }}</el-descriptions-item>
        <el-descriptions-item label="客户姓名">{{ currentLoan.customerName }}</el-descriptions-item>
        <el-descriptions-item label="放款金额">{{ formatAmount(currentLoan.amount) }}</el-descriptions-item>
        <el-descriptions-item label="收款账号">{{ currentLoan.bankAccount }}</el-descriptions-item>
        <el-descriptions-item label="开户行">{{ currentLoan.bankName }}</el-descriptions-item>
        <el-descriptions-item label="支付渠道">{{ currentLoan.payChannel }}</el-descriptions-item>
      </el-descriptions>

      <!-- 处理记录 -->
      <el-timeline style="margin-top: 20px">
        <el-timeline-item
          v-for="(activity, index) in processHistory"
          :key="index"
          :type="activity.type"
          :color="activity.color"
          :timestamp="activity.timestamp"
        >
          {{ activity.content }}
          <p v-if="activity.remark" style="color: #666; margin: 5px 0">
            备注：{{ activity.remark }}
          </p>
        </el-timeline-item>
      </el-timeline>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { lendingApi } from '@/api/lending'

export default {
  name: 'LendingProcess',
  setup() {
    // 搜索表单
    const searchForm = reactive({
      loanNo: '',
      customerName: '',
      status: ''
    })

    // 状态管理
    const loading = ref(false)
    const processList = ref([])
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const processDialogVisible = ref(false)
    const activeStep = ref(0)
    const currentLoan = ref({})
    const detailDialogVisible = ref(false)

    // 表单数据
    const verifyFormRef = ref(null)
    const verifyForm = reactive({
      infoConfirm: false,
      remark: ''
    })

    const fundFormRef = ref(null)
    const fundForm = reactive({
      fundSource: '',
      prepareTime: '',
      confirmor: '',
      remark: ''
    })

    const executeFormRef = ref(null)
    const executeForm = reactive({
      transactionNo: '',
      executeTime: new Date(),
      channel: '',
      remark: ''
    })

    const confirmFormRef = ref(null)
    const confirmForm = reactive({
      status: 'success',
      remark: ''
    })

    // 获取待处理放款列表
    const getPendingList = async () => {
      try {
        loading.value = true
        const params = {
          loanNo: searchForm.loanNo,
          customerName: searchForm.customerName,
          pageNum: currentPage.value,
          pageSize: pageSize.value
        }
        
        const res = await lendingApi.getPendingList(params)
        processList.value = res.data.list
        total.value = res.data.total
      } catch (error) {
        console.error('获取放款列表失败', error)
        ElMessage.error('获取放款列表失败')
      } finally {
        loading.value = false
      }
    }

    // 查看详情
    const viewDetail = async (row) => {
      try {
        loading.value = true
        const res = await lendingApi.getDetail(row.disbursementId || row.contractId)
        currentLoan.value = res.data
        detailDialogVisible.value = true
      } catch (error) {
        console.error('获取详情失败', error)
        ElMessage.error('获取详情失败')
      } finally {
        loading.value = false
      }
    }

    // 处理放款
    const handleProcess = (row) => {
      currentLoan.value = row
      processDialogVisible.value = true
      activeStep.value = 0
      // 重置表单数据
      verifyForm.infoConfirm = false
      verifyForm.remark = ''
    }

    // 处理放款确认
    const handleConfirm = (row) => {
      currentLoan.value = row
      processDialogVisible.value = true
      activeStep.value = 3
    }

    // 下一步
    const nextStep = async () => {
      // 根据当前步骤进行表单验证和数据处理
      if (activeStep.value === 0) {
        if (!verifyForm.infoConfirm) {
          ElMessage.warning('请确认放款信息无误')
          return
        }
        activeStep.value++
      } else if (activeStep.value === 1) {
        if (!fundForm.fundSource || !fundForm.prepareTime) {
          ElMessage.warning('请完成资金准备信息')
          return
        }
        activeStep.value++
      } else if (activeStep.value === 2) {
        if (!executeForm.transactionNo || !executeForm.channel) {
          ElMessage.warning('请完成执行信息')
          return
        }
        
        try {
          loading.value = true
          
          // 准备放款处理数据
          const processData = {
            disbursementId: currentLoan.value.disbursementId || currentLoan.value.contractId,
            disburseTime: executeForm.executeTime.toISOString().slice(0, 19).replace('T', ' '),
            transactionNo: executeForm.transactionNo,
            status: '30', // 放款成功
            remark: executeForm.remark
          }
          
          await lendingApi.process(processData)
          
          ElMessage.success('放款执行成功')
          activeStep.value++
        } catch (error) {
          console.error('放款执行失败', error)
          ElMessage.error('放款执行失败：' + (error.message || '未知错误'))
        } finally {
          loading.value = false
        }
      } else if (activeStep.value === 3) {
        processDialogVisible.value = false
        getPendingList() // 刷新列表
      }
    }

    // 上一步
    const prevStep = () => {
      if (activeStep.value > 0) {
        activeStep.value--
      }
    }

    // 提交放款申请
    const submitLendingApplication = async () => {
      try {
        loading.value = true
        
        // 准备放款申请数据
        const applyData = {
          contractId: currentLoan.value.contractId,
          amount: currentLoan.value.amount,
          bankName: currentLoan.value.bankName,
          bankAccount: currentLoan.value.bankAccount,
          accountName: currentLoan.value.customerName,
          disburseDate: new Date().toISOString().split('T')[0],
          remark: verifyForm.remark
        }
        
        const res = await lendingApi.apply(applyData)
        
        ElMessage.success('放款申请提交成功')
        
        // 更新当前记录中的放款ID
        currentLoan.value.disbursementId = res.data.disbursementId
        
        // 进入下一步
        activeStep.value++
      } catch (error) {
        console.error('放款申请提交失败', error)
        ElMessage.error('放款申请提交失败：' + (error.message || '未知错误'))
      } finally {
        loading.value = false
      }
    }

    // 处理搜索
    const handleSearch = () => {
      currentPage.value = 1
      getPendingList()
    }

    // 重置搜索
    const resetSearch = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''
      })
      currentPage.value = 1
      getPendingList()
    }

    // 分页处理
    const handleSizeChange = (val) => {
      pageSize.value = val
      getPendingList()
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      getPendingList()
    }

    // 格式化金额
    const formatAmount = (amount) => {
      if (!amount && amount !== 0) return '--'
      return Number(amount).toLocaleString('zh-CN', {
        style: 'currency',
        currency: 'CNY',
        minimumFractionDigits: 2
      })
    }

    // 获取状态类型
    const getStatusType = (status) => {
      const statusMap = {
        'pending': 'warning',
        'processing': 'primary',
        'completed': 'success',
        'failed': 'danger'
      }
      return statusMap[status] || 'info'
    }

    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        'pending': '待处理',
        'processing': '处理中',
        'completed': '已完成',
        'failed': '处理失败'
      }
      return statusMap[status] || '未知状态'
    }

    // 获取进度状态
    const getProgressStatus = (status) => {
      const statusMap = {
        'pending': '',
        'processing': '',
        'completed': 'success',
        'failed': 'exception'
      }
      return statusMap[status] || ''
    }

    onMounted(() => {
      getPendingList()
    })

    return {
      searchForm,
      loading,
      processList,
      total,
      currentPage,
      pageSize,
      processDialogVisible,
      activeStep,
      currentLoan,
      detailDialogVisible,
      verifyFormRef,
      verifyForm,
      fundFormRef,
      fundForm,
      executeFormRef,
      executeForm,
      confirmFormRef,
      confirmForm,
      getPendingList,
      viewDetail,
      handleProcess,
      handleConfirm,
      nextStep,
      prevStep,
      submitLendingApplication,
      handleSearch,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      formatAmount,
      getStatusType,
      getStatusText,
      getProgressStatus
    }
  }
}
</script>

<style scoped>
.lending-process {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.process-steps {
  margin: 20px 0 40px;
}

.step-content {
  min-height: 300px;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.amount-text {
  color: #409EFF;
  font-size: 16px;
  font-weight: bold;
}

:deep(.el-descriptions) {
  margin-bottom: 20px;
}

:deep(.el-timeline) {
  margin-top: 20px;
  padding: 20px;
}
</style> 